import strPageTitleHtml from "./PageTitle.html"; // 使用 raw-loader 加载 HTML 文件
import { DomUtils } from "../../utils/DomUtils"; // 引入 DomUtils 类

import { routerStore } from "../../stores/routerStore";

export class PageTitle {
  constructor(data) {
    // 如果没有传递数据，则使用默认数据
    // 合并传入数据与默认值
    this.data = {
      title: "",
      breadcrumb: [],
      ...data,
    };
    this.dom = null;
    this.unsubscribe = null;
  }

  render() {
    // 渲染面包屑
    let breadcrumbHtml = this.data.breadcrumb
      .map((item) => {
        return `<li class="breadcrumb-item">
              <a href="${item.link}">${item.text}</a>
            </li>`;
      })
      .join("");

    // 将数据动态替换到 HTML 模板中
    const pageTitleHtml = strPageTitleHtml
      .replace("{{title}}", this.data.title)
      .replace("{{breadcrumb}}", breadcrumbHtml);

    this.dom = DomUtils.convertToDom(pageTitleHtml);

    // 订阅路由变化
    this.unsubscribe = routerStore.subscribe(
      (state) => state.currentPath,
      (currentPath) => {
        this.updateBreadcrumb(currentPath);
      }
    );

    return this.dom;
  }

  updateBreadcrumb(path) {
    // 根据路径生成面包屑
    const pathSegments = path.split("/").filter((segment) => segment);
    const breadcrumb = [];

    // 添加首页
    breadcrumb.push({ text: "首页", link: "/home" });

    // 根据路径生成面包屑项
    let currentPath = "";
    pathSegments.forEach((segment, index) => {
      currentPath += `/${segment}`;
      const text = this.getBreadcrumbText(segment);
      if (text) {
        breadcrumb.push({
          text: text,
          link: currentPath,
        });
      }
    });

    // 更新面包屑HTML
    const breadcrumbHtml = breadcrumb
      .map((item, index) => {
        const isLast = index === breadcrumb.length - 1;
        return `<li class="breadcrumb-item ${isLast ? "active" : ""}">
          ${isLast ? item.text : `<a href="${item.link}">${item.text}</a>`}
        </li>`;
      })
      .join("");

    const breadcrumbContainer = this.dom.querySelector(".breadcrumb");
    if (breadcrumbContainer) {
      breadcrumbContainer.innerHTML = breadcrumbHtml;
    }
  }

  getBreadcrumbText(segment) {
    // 路径段到显示文本的映射
    const pathMap = {
      market: "商城",
      cart: "购物车",
      "my-orders": "我的订单",
      knowledge: "知识库",
      community: "社区",
      "farmer-orders": "订单管理",
      "farmer-products": "商品管理",
      "admin-products": "商品管理",
      "admin-orders": "订单管理",
      video: "视频管理",
      user: "用户管理",
    };

    return pathMap[segment] || segment;
  }
}
